<template>
  <el-checkbox-group
    :modelValue="val"
    :disabled="ui.disabled"
    :text-color="ui.textColor"
    :size="service.size"
    :fill="ui.fill"
    :max="ui.max"
    :min="ui.min"
    @update:model-value="updateValue"
  >
    <template v-for="(item, i) in items" :key="i">
      <el-checkbox-button
        v-if="!item.hidden && ui.moda === 'button'"
        :label="item.value"
        :border="ui.border"
        :checked="item.checked"
        :disabled="item.disabled"
        >{{ item.label }}</el-checkbox-button
      >
      <el-checkbox
        v-else-if="!item.hidden"
        :label="item.value"
        :border="ui.border"
        :checked="item.checked"
        :disabled="item.disabled"
        >{{ item.label }}</el-checkbox
      >
    </template>
  </el-checkbox-group>
</template>
<script lang="ts" setup name="lc-sf-checkbox">
import { asyncComputed } from "@vueuse/core";
import { inject, computed } from "vue";
import { CheckBoxUI, CheckBoxEnum } from "../interface";
import { SFService } from "../sf.service";
import { TItemOption } from "../type";
const props = defineProps<TItemOption<CheckBoxUI>>();
const sf = inject<SFService>("sf-service");
const val = computed(() => {
  return sf.getVaule(props.keyPath);
});
const ui = props.service.getUI<CheckBoxUI>();
const items = asyncComputed(async () => {
  let result = [];
  if (typeof ui.items === "function") {
    if (ui.items instanceof Promise) {
      result = (await ui.items()) || [];
    }
    result = (ui.items as () => CheckBoxEnum[])() || [];
  } else {
    result = ui.items || [];
  }
  setValue(result);
  return result;
});
const updateValue = (val: string[] | number[]) => {
  if (ui.change) {
    ui.change(val);
  }
  sf.setVaule(props.keyPath, val);
};
const setValue = (enums: CheckBoxEnum[]) => {
  const checkVal = enums.filter(e => e.checked).map(e => e.value);
  if (!val.value) {
    sf.setVaule(props.keyPath, checkVal);
  }
};
</script>

<style />
../types
